package com.example.jazztalk.service;

import java.util.ArrayList;

import com.example.jazztalk.common.IJazzTalkService;
import com.ibm.team.repository.common.IItem;
import com.ibm.team.repository.common.IItemType;
import com.ibm.team.repository.common.TeamRepositoryException;
import com.ibm.team.repository.common.query.IItemQuery;
import com.ibm.team.repository.common.query.IItemQueryPage;
import com.ibm.team.repository.common.service.IQueryService;
import com.ibm.team.repository.service.AbstractService;
import com.ibm.team.repository.service.IRepositoryItemService;

import example.jazztalk.common.model.JazztalkPackage;
import example.jazztalk.common.model.Message;
import example.jazztalk.common.model.query.BaseMessageQueryModel;
import example.jazztalk.common.model.query.BaseMessageQueryModel.MessageQueryModel;

public class JazzTalkService extends AbstractService implements IJazzTalkService {

   public Message[] getAllMessages() throws TeamRepositoryException {
      IQueryService queryService = getService(IQueryService.class);
      
      MessageQueryModel queryModel = BaseMessageQueryModel.MessageQueryModel.ROOT;
      IItemQuery itemQuery = IItemQuery.FACTORY.newInstance(queryModel);
      
      IItemQueryPage itemQueryPage = queryService.queryItems(itemQuery,
         IQueryService.EMPTY_PARAMETERS, IQueryService.ITEM_QUERY_MAX_PAGE_SIZE);
      
      IRepositoryItemService repositoryItemService = getService(IRepositoryItemService.class);
      IItem[] items = repositoryItemService.fetchItems(itemQueryPage.handlesAsArray(), null);
      ArrayList<Message> messages = new ArrayList<Message>();
      for (IItem item : items) {
         if (item instanceof Message) {
            messages.add((Message) item);
         }
      }
      
      return (Message[]) messages.toArray(new Message[messages.size()]);
      
   }

   public Message postNewMessage(NewMessageParameters params)
         throws TeamRepositoryException {
      IRepositoryItemService repositoryItemService = getService(IRepositoryItemService.class);
       Message message = (Message) getMessageItemType().createItem();
      message.setText(params.text);
      message = (Message) repositoryItemService.saveItem(message);
      return message;
   }
   
   
   static IItemType getMessageItemType() {
      return IItemType.IRegistry.INSTANCE
      .getItemType(JazztalkPackage.eINSTANCE.getMessage().getName(), JazztalkPackage.eNS_URI);
   }
   
}
